<style scoped lang="scss">
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>

<template>
  <div ref="baseChart" class="chart-container"></div>
</template>

<script>
import * as echarts from 'echarts';
import elementResizeDetectorMaker from 'element-resize-detector';

const mouseEvents = [
  'click',
  'dblclick',
  'mousedown',
  'mousemove',
  'mouseup',
  'mouseover',
  'mouseout',
  'globalout',
  'contextmenu'
];

export default {
  name: 'BaseChart',
  components: {},
  props: {
    dataList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      baseChart: null,
      chartConfig: {}
    };
  },
  computed: {},
  watch: {
    dataList: {
      handler() {
        this._refreshChart();
      },
      deep: true
    }
  },
  created() {},
  mounted() {
    this.init();
  },
  beforeDestroy() {
    if (this.baseChart) {
      this.baseChart.dispose();
      this.baseChart = null;
    }
  },
  methods: {
    init(chartConfig) {
      this.chartConfig = chartConfig;
      this._initChart();
      this.$nextTick(() => {
        this._refreshChart();
        this.initListenToDiv();
      });
    },
    _initChart() {
      this.baseChart = echarts.init(this.$refs.baseChart);
      mouseEvents.forEach(eventName => {
        this.baseChart.on(eventName, params => {
          this.$emit(eventName, params, this.baseChart);
        });
      });
    },
    initListenToDiv() {
      let erd = elementResizeDetectorMaker();
      let that = this;
      erd.listenTo(this.$refs.baseChart, () => {
        that.$nextTick(function () {
            // 使echarts尺寸重置
          that.baseChart.resize();
        });
      });
    },
    _refreshChart() {
      if (!this.baseChart) {
        this._initChart();
      }
      this.baseChart.clear();
      const options = this.makeOptions();
      this.baseChart.setOption(options);
    },
    makeOptions() {
      throw new Error('please implement makeOptions function');
    }
  }
};
</script>
